package com.duan.laugh.starter.email;

import com.fasterxml.jackson.annotation.JsonAutoDetect;
import com.fasterxml.jackson.annotation.PropertyAccessor;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.datatype.jdk8.Jdk8Module;
import com.fasterxml.jackson.datatype.jsr310.JavaTimeModule;
import com.fasterxml.jackson.module.paramnames.ParameterNamesModule;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.Jackson2JsonRedisSerializer;

import java.util.List;

/**
 * reids中的邮箱账户
 *
 * @author duanjw
 */
public class RedisEmailAccountRepository implements EmailAccountRepository {
    /**
     * 邮箱账户redis中的key
     */
    private final String emailAccountKey = "email::accounts::key";
    private RedisTemplate redisTemplate;

    public RedisEmailAccountRepository(RedisConnectionFactory redisConnectionFactory) {
        redisTemplate = new RedisTemplate();
        redisTemplate.setConnectionFactory(redisConnectionFactory);
        final Jackson2JsonRedisSerializer<EmailAccount> jackson2JsonRedisSerializer = new Jackson2JsonRedisSerializer<>(EmailAccount.class);
        ObjectMapper objectMapper = new ObjectMapper();
        // 支持JAVA8时间格式
        objectMapper.registerModule(new ParameterNamesModule())
                .registerModule(new Jdk8Module())
                .registerModule(new JavaTimeModule());
        jackson2JsonRedisSerializer.setObjectMapper(objectMapper);
        redisTemplate.setKeySerializer(redisTemplate.getStringSerializer());
        redisTemplate.setValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.setHashKeySerializer(redisTemplate.getStringSerializer());
        redisTemplate.setHashValueSerializer(jackson2JsonRedisSerializer);
        redisTemplate.afterPropertiesSet();
    }

    /**
     * 所有邮箱账户
     * @return
     */
    @Override
    public List<EmailAccount> getEmailAccounts() {
        return redisTemplate.opsForHash().values(emailAccountKey);
    }

    /**
     * 根据邮箱账户id获取邮箱账户
     * @param id
     * @return
     */
    @Override
    public EmailAccount getEmailAccount(String id) {
        return (EmailAccount) redisTemplate.opsForHash().get(emailAccountKey, id);
    }

    /**
     * 新增邮箱账户
     * @param emailAccount
     */
    @Override
    public void add(EmailAccount emailAccount) {
        redisTemplate.opsForHash().put(emailAccountKey, emailAccount.getId(), emailAccount);
    }

    /**
     * 根据id删除邮箱账户
     * @param id
     */
    @Override
    public void delete(String id) {
        redisTemplate.opsForHash().delete(emailAccountKey, id);
    }
}
